package vip.xiaonuo.biz.modular.Englishword;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import vip.xiaonuo.biz.core.config.QianWenConfig;
import vip.xiaonuo.biz.modular.Englishword.param.BatchParam;
import vip.xiaonuo.biz.modular.Englishword.result.BatchResult;
import vip.xiaonuo.biz.modular.Englishword.result.FileResult;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

@RestController
@RequestMapping("/ai")
public class AIController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private QianWenConfig openAIConfig;

    // 上传文件
    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") FileSystemResource file) {
        // 构建请求头和请求体
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.set("Authorization", "Bearer " + openAIConfig.getApiKey());

        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", file);
        body.add("purpose", "batch");

        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        // 发送请求
        ResponseEntity<FileResult> response = restTemplate.postForEntity(
                openAIConfig.getBaseUrl() + "/files", requestEntity, FileResult.class);

        return response.getBody().getId();
    }

    // 创建Batch任务
    @PostMapping("/batch")
    public String createBatchJob(@RequestParam("fileId") String fileId) {
        // 构建请求体
        BatchParam batchParam = new BatchParam(
                fileId, "/v1/chat/completions", "24h");

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + openAIConfig.getApiKey());

        HttpEntity<BatchParam> requestEntity = new HttpEntity<>(batchParam, headers);

        // 发送请求
        ResponseEntity<BatchResult> response = restTemplate.postForEntity(
                openAIConfig.getBaseUrl() + "/batches", requestEntity, BatchResult.class);

        return response.getBody().getId();
    }

    // 检查Batch任务状态
    @GetMapping("/batch/{batchId}")
    public String checkJobStatus(@PathVariable("batchId") String batchId) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + openAIConfig.getApiKey());

        HttpEntity<Void> requestEntity = new HttpEntity<>(headers);

        // 发送请求
        ResponseEntity<BatchResult> response = restTemplate.exchange(
                openAIConfig.getBaseUrl() + "/batches/" + batchId, HttpMethod.GET, requestEntity, BatchResult.class);

        return response.getBody().getStatus();
    }

    // 获取输出文件ID
    @GetMapping("/batch/output/{batchId}")
    public String getOutputId(@PathVariable("batchId") String batchId) {
        // 检查Batch任务状态
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + openAIConfig.getApiKey());

        HttpEntity<Void> requestEntity = new HttpEntity<>(headers);

        // 发送请求
        ResponseEntity<BatchResult> response = restTemplate.exchange(
                openAIConfig.getBaseUrl() + "/batches/" + batchId, HttpMethod.GET, requestEntity, BatchResult.class);

        return response.getBody().getOutputFileId();
    }

    // 获取错误文件ID
    @GetMapping("/batch/error/{batchId}")
    public String getErrorId(@PathVariable("batchId") String batchId) {
        // 检查Batch任务状态
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + openAIConfig.getApiKey());

        HttpEntity<Void> requestEntity = new HttpEntity<>(headers);

        // 发送请求
        ResponseEntity<BatchResult> response = restTemplate.exchange(
                openAIConfig.getBaseUrl() + "/batches/" + batchId, HttpMethod.GET, requestEntity, BatchResult.class);

        return response.getBody().getErrorFileId();
    }

    // 下载结果文件
    @GetMapping("/file/content/{fileId}")
    public void downloadResults(@PathVariable("fileId") String fileId, @RequestParam("filePath") String filePath) throws IOException {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + openAIConfig.getApiKey());

        HttpEntity<Void> requestEntity = new HttpEntity<>(headers);

        // 发送请求
        ResponseEntity<String> response = restTemplate.exchange(
                openAIConfig.getBaseUrl() + "/files/" + fileId + "/content", HttpMethod.GET, requestEntity, String.class);

        // 保存文件
        Files.write(Path.of(filePath), response.getBody().getBytes());
    }

}